package com.ayf.payment.game.api.controller.player;


import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.integral.service.remote.OSSRemoteService;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @Description: 文件控制层
 * @Author: zh-liang
 * @Date : 2020-06-09 14:43
 */
@Controller
@RequestMapping("/v/file")
public class FileController {

    private static final String PLATFORM_CODE = System.getenv("GAME_AYFPAY_PLATFORM_CODE").toLowerCase();

    @Reference(version = "1.0.0",check = false)
    private OSSRemoteService ossRemoteService;

    /**
     * 图片上传
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/uploadGoodImg")
    public CommonResult<String> upload(@RequestParam("file") MultipartFile file, MerchantDTO merchantDTO) {
        String traceId = SnowFlakeUtils.getUniqueId();
        String fileName = "integral_good/" + PLATFORM_CODE + "/" + merchantDTO.getId() + "/" + traceId;
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg".equals(suffix) && !"png".equals(suffix) && !"jpeg".equals(suffix)) {
            LogPortal.error("{} 商户[{}]图片上传失败，文件格式错误，仅支持jpg、png、jpeg，当前文件格式：{}", traceId, merchantDTO.getId(), suffix);
            throw new ParameterException("上传失败，图片格式错误，仅支持jpg、png、jpeg格式");
        }
        if (file.getSize() > 1024 * 1100) {
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "图片过大，仅支持1M之下的图片");
        }
        try {
            String url = ossRemoteService.uploadImg(suffix.toLowerCase(), file.getBytes(), fileName);
            return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "上传成功", url);
        } catch (Exception e) {
            LogPortal.error("[{}]图片上传发生[{}]异常,异常信息为[{}]", traceId, e.getClass().getSimpleName(), e.getMessage());
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "上传失败，错误码：" + traceId);
        }
    }

    /**
     * 文件下载
     *
     * @param fileName
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/download")
    public void downloadFile(HttpServletResponse response, @RequestParam("fileName") String fileName, @RequestParam(
            "type") String type) {
        String traceId = SnowFlakeUtils.getUniqueId();
        ServletOutputStream outputStream = null;
        try {
            byte[] bytes;
            if ("1".equals(type)) {
                bytes = ossRemoteService.downloadFile(fileName);
            } else {
                bytes = ossRemoteService.downloadThumbFile(fileName);
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Cache-Control", "No-cache");
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (Exception e) {
            LogPortal.error("[{}]文件下载发生[{}]异常,异常信息为[{}]", e, traceId, e.getClass().getSimpleName(), e.getMessage());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                LogPortal.error("文件上传关闭流时发生IOException，异常信息为: {}", e, e.getMessage());
            }
        }
    }

}
